<template>
  <div class="role-container">
    <el-row type="flex">
      <el-col :span="10">
        <div class="app-container calendar-list-container">
          <el-form>
            <el-row class="row-bg" justify="space-around" type="flex">
              <el-col :span="20">
                <el-form-item label="角色名称">
                  <el-input v-model="queryCondition.roleName"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="0"
                    class="cutOffLine">
              <div class="buttonGroup">
                <el-button @click="checkRoleTreeByName"
                           size="small"
                           type="primary">
                  <icon name="search"></icon>
                  查询
                </el-button>
              </div>
            </el-row>
          </el-form>
        </div>
        <el-tree
          :check-strictly="true"
          :data="roleTree"
          :expand-on-click-node="false"
          :props="defaultRoleProps"
          @check="checkRoleTree"
          default-expand-all
          node-key="id"
          ref="roleTree"
          show-checkbox>
          <span class="custom-tree-node" slot-scope="{ node, data } ">
            <el-input :placeholder="node.label"
                      v-if="data.isEdit"
                      v-model="modifyRoleName"/>
            <span v-else>{{ node.label }}</span>
            <span v-if="data.isEdit">
              <el-button
                @click="() => finish(data)"
                size="mini"
                type="text">
                完成
              </el-button>
              <el-button
                @click="() => cancel(node, data)"
                size="mini"
                type="text">
                取消
              </el-button>
            </span>
            <span v-else>
              <el-button
                @click="() => add(data)"
                size="mini"
                type="text"
                v-if="isAddMode == false && isEditMode == false">
                添加
              </el-button>
              <el-button
                @click="() => modify(data)"
                size="mini"
                type="text"
                v-if="isAddMode == false && isEditMode == false && data.id !== -1">
                修改
              </el-button>
              <el-button
                @click="() => deleteRole(data)"
                size="mini"
                type="text"
                v-if="isAddMode == false && isEditMode == false && data.id !== -1">
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="14">
        <div class="app-container calendar-list-container"
             v-show="showPermitTree">
          <div v-if="permitRootList!=null">
            <div class="filter-container">
              <el-button @click="updateRolePermitList"
                         ref="savePermit"
                         size="small"
                         type="primary"
                         v-show="editable">
                保存
              </el-button>
              <el-button @click="cancelEdit"
                         ref="cancel"
                         size="small"
                         type="primary"
                         v-show="editable">
                取消
              </el-button>
              <el-button @click="resetChecked"
                         ref="resetPermit"
                         size="small"
                         type="danger"
                         v-show="editable">
                清空
              </el-button>
              <el-button @click="enableEdit"
                         id="editPermit"
                         size="small"
                         type="primary"
                         v-show="showEditBtn">
                <icon name="user"></icon>
                权限管理
              </el-button>
            </div>
            <br/>
            <el-collapse id="treeItems"
                         style="overflow: auto;height: 672px; margin-top:-10px;"
                         v-model="activeSubSystems">
              <el-collapse-item :key="permitNode.clientType"
                                :name=permitNode.clientType
                                v-for="permitNode in permitRootList">
                <template slot="title">
                  <span>{{permitNode.clientType | displayLabelValue(clientType)}}</span>
                </template>
                <el-tree :data=permitNode.subMenu
                         :filter-node-method="filterNode"
                         :props="defaultPermitProps"
                         default-expand-all
                         highlight-current
                         node-key="id"
                         ref="tree"
                         show-checkbox>
                </el-tree>
              </el-collapse-item>

            </el-collapse>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-dialog :title="title"
               :visible.sync="showUserByRoleDialog"
               @open="showUserByRoleDialogOpen"
               width="60%">
      <el-table :data="userByRoleIdList"
                border
                element-loading-spinner="el-icon-loading"
                element-loading-text="加载中"
                fit
                highlight-current-row
                stripe>
        <el-table-column align="left"
                         label="用户账号"
                         property="userId"
                         width="300"></el-table-column>
        <el-table-column align="left"
                         label="用户名称"
                         property="name"
                         width="300"></el-table-column>
        <el-table-column align="center"
                         label="用户状态"
                         property="statusText">
          <template slot-scope="scope">
            <span>{{scope.row.status === '1' ? '可用': '不可用'}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data () {
    return {
      rules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {max: 40, message: '长度不大于50', trigger: 'blur'},
          {pattern: /^[\u2E80-\u9FFF]+$/, message: '角色名只允许汉字'}
        ],
        roleId: [
          {max: 6, message: '长度不大于6', trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: '角色ID只允许数字'}
        ]
      },
      apiName: {
        queryAllPermitList: this.apiType.admin.queryAllPermitList,
        queryPermitListByRoleIdList: this.apiType.admin.queryPermitListByRoleIdList,
        queryRoleTree: this.apiType.admin.queryRoleTree,
        addRole: this.apiType.admin.addRole,
        modifyRole: this.apiType.admin.modifyRole,
        deleteRole: this.apiType.admin.deleteRole,
        bindRolPermitList: this.apiType.admin.bindRolePermit,

        queryRoleList: this.apiType.admin.queryRoleList,
        queryDictList: this.apiType.queryDictList,
        queryRoleUser: this.apiType.queryRoleUser
      },
      queryCondition: {
        roleName: '',
        parentRoleName: ''
      },
      isAddMode: false,
      isEditMode: false,
      modifyRoleName: '',
      rootRole: {
        isEdit: false
      },
      roleTree: [{
        id: -1,
        name: '角色树',
        disabled: true,
        subRole: []
      }],

      isEdit: '',
      title: '',
      roleDialog: false,
      showUserByRoleDialog: false,
      formLabelWidth: '120px',
      dict: {
        subSystemList: [{label: '全系统', value: '全系统'}]
      },
      roleForm: {
        roleId: '',
        parentRoleId: '',
        name: '',
        prefixName: '全系统'
      },
      oldName: '',
      oldParentRoleId: '',
      roleList: [],
      userByRoleIdList: [],
      currentPage: 1,
      pageSize: 20,
      totalCount: 0,
      permitRootList: '',
      rolePermitList: '',
      subList: '',
      editable: '',
      showEditBtn: '',
      showPermitTree: true,
      activeSubSystems: '',
      currentRow: null,
      currentSelectRoleId: '',
      defaultPermitProps: {
        children: 'subMenu',
        label: 'showName'
      },
      defaultRoleProps: {
        children: 'subRole',
        label: 'name'
      }
    }
  },
  mounted () {
    this.queryRoleTree()
    // this.querySubSystemList()
    this.queryAllPermitList()
  },
  watch: {
    currentSelectRoleId (val) {
      this.$refs.roleTree.setCheckedKeys([val])
      this.showRolePermitList(val)
    }
  },
  methods: {
    check (arg) {
      console.log(arg)
    },
    add (data) {
      const newChild = {
        id: -1,
        parentRoleId: data.id !== -1 ? data.id : null,
        name: '新建角色',
        subRole: [],
        'isEdit': true
      }
      if (!data.subRole) {
        this.$set(data, 'subRole', [])
      }
      data.subRole.push(newChild)
      this.isAddMode = true
    },
    cancel (node, data) {
      this.$set(data, 'isEdit', false)
      if (this.isAddMode) {
        const parent = node.parent
        const children = parent.data.subRole || parent.data
        const index = children.findIndex(d => d.id === data.id)
        children.splice(index, 1)
      }
      this.isEditMode = false
      this.isAddMode = false
    },
    modify (data) {
      this.$set(data, 'isEdit', true)
      this.modifyRoleName = data.name
      this.isEditMode = true
    },
    finish (data) {
      this.$set(data, 'isEdit', false)
      this.$set(data, 'name', this.modifyRoleName)
      this.modifyRoleName = ''
      if (this.isEditMode) {
        this.modifyRole(data)
        this.isEditMode = false
      }
      if (this.isAddMode) {
        this.addRole(data)
        this.isAddMode = false
      }
    },
    checkRoleTree (checkedNodes, checkedKeys) {
      if (checkedKeys.checkedKeys.indexOf(checkedNodes.id) === -1) {
        this.currentSelectRoleId = ''
      } else {
        this.currentSelectRoleId = checkedNodes.id
      }
    },
    showUserByRoleDialogOpen () {
      this.queryUserByRoleIdList()
    },
    queryUserByRoleIdList () {
      const param = {
        roleId: this.currentSelectRoleId
      }
      this.ajaxPermit(
        this.apiName.queryRoleUser,
        this.serviceType().query,
        param,
        responseData => {
          const data = responseData.body || []
          this.userByRoleIdList = data
        },
        responseData => {
          this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    querySubSystemList () {
      const _this = this
      const param = {dictId: 'TRADE_WAY'}
      this.ajaxPermit(
        this.apiName.queryDictList,
        this.serviceType().query,
        param,
        responseData => {
          const dict = responseData.body || []
          _this.dict.subSystemList = _this.dict.subSystemList.concat(dict)
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    toggleSelection (row) {
      this.currentSelectRoleId = row.id
    },
    clearForm (formName) {
      this.$refs[formName].resetFields()
    },
    setData () {
      this.roleForm.roleId = this.currentRow.roleId
      this.roleForm.parentRoleId = this.currentRow.parentRoleId
      this.formatRoleName(this.currentRow.name)
      this.oldName = this.currentRow.name
      this.oldParentRoleId = this.currentRow.parentRoleId === null ? '' : this.currentRow.parentRoleId
    },
    resetChecked () {
      const trees = this.$refs.tree
      for (const item in trees) {
        trees[item].setCheckedKeys([])
      }
    },
    expandAllPermitList (param, needFilter, needExpandTabs) {
      needExpandTabs = needExpandTabs || []
      const items = param
      const nameArray = []
      items.forEach(item => {
        if (needFilter) {
          if (needExpandTabs.indexOf(item.clientType) > -1) {
            nameArray.push(item.clientType)
          }
        } else {
          nameArray.push(item.clientType)
        }
      })
      this.activeSubSystems = nameArray
    },
    queryRoleTree () {
      const _this = this
      this.fetch(this.apiName.queryRoleTree, null, null, responseData => {
        _this.roleTree[0].subRole = responseData.data || []
      })
    },
    checkRoleTreeByName () {
      const node = this.findNode(this.queryCondition.roleName, this.roleTree[0].subRole)
      if (node) {
        this.currentSelectRoleId = node.id
      }
    },
    findNode (name, treeRoot) {
      for (let node in treeRoot) {
        if (treeRoot[node].name.indexOf(name) !== -1) {
          return treeRoot[node]
        }
      }
      if (treeRoot.subRole) {
        return this.findNode(name, treeRoot.subRole)
      }
    },
    queryRoleList () {
      const _this = this
      const param = {
        roleName: this.queryCondition.roleName,
        parentRoleName: this.queryCondition.parentRoleName
      }
      this.fetch(this.apiName.queryRoleList, param, null, responseData => {
        _this.roleList = responseData.data || []
      })
    },
    changeSize () {
      this._data.tpageSize = this.pageSize
    },
    handleCurrentChange (currentPage) {
      this.$emit('currentPageChange', currentPage)
      this.currentPage = currentPage
      this.queryRoleList()
    },
    setDatalist (arr) {
      console.log('setDatalist')
      this.roleList = JSON.parse(JSON.stringify(arr))
      console.log(this.roleList)
    },
    showAddRoleDialog () {
      this.title = '新增角色'
      this.isEdit = false
      this.isAdd = true
      this.currentSelectRoleId = ''
      this.setCurrent()
      this.roleDialog = true
      this.showPermitTree = false
      this.currentRow = ''
    },
    setCurrent (row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    handleCurrentRowChange (val) {
      this.currentRow = val
    },
    addRole (role) {
      const _this = this
      const body = {
        parentRoleId: role.parentRoleId,
        name: role.name
      }
      this.fetch(
        this.apiName.addRole,
        null,
        body,
        () => {
          _this.$message({
            showClose: true,
            message: '新增角色成功',
            type: 'success',
            duration: 2000
          })
          _this.queryRoleTree()
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    modifyRole (role) {
      const _this = this
      const body = {
        id: role.id,
        parentRoleId: role.parentRoleId,
        name: role.name
      }
      this.fetch(
        this.apiName.modifyRole,
        null,
        body,
        () => {
          _this.$message({
            showClose: true,
            message: '修改角色成功',
            type: 'success',
            duration: 2000
          })
          _this.queryRoleTree()
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    deleteRole (role) {
      const _this = this
      const body = {
        id: role.id
      }
      this.fetch(
        this.apiName.deleteRole,
        null,
        body,
        () => {
          _this.$message({
            showClose: true,
            message: '删除角色成功',
            type: 'success',
            duration: 2000
          })
          _this.queryRoleTree()
        })
    },
    disableEdit () {
      this.editable = false
      this.showEditBtn = true
      this.disableAllCheckBox(this.permitRootList)
    },
    enableEdit () {
      this.editable = true
      this.showEditBtn = false
      this.expandAllPermitList(this.permitRootList, false)
      this.showAll()
      this.enableAllCheckBox(this.permitRootList)
    },
    showAll () {
      const trees = this.$refs.tree
      for (const item in trees) {
        trees[item].filter(1)
      }
    },

    cancelEdit () {
      this.showRolePermitList()
      this.disableEdit()
    },
    // 使checkbox禁选
    disableAllCheckBox (data) {
      data = data || []
      data.forEach(item => {
        item.disabled = true
        if (item.subMenu) {
          this.disableAllCheckBox(item.subMenu)
        }
      })
    },
    // 使checkbox可选
    enableAllCheckBox (data) {
      data = data || []
      data.forEach(item => {
        item.disabled = false
        if (item.subMenu) {
          this.enableAllCheckBox(item.subMenu)
        }
      })
    },
    filterNode (value, data) {
      if (this.editable) {
        return true
      }
      if (!value) {
        return false
      }
      for (const item in value) {
        if (data.id === value[item]) {
          return true
        }
        if (data.id === value[item].id) {
          return true
        }
      }
      return false
    },
    // 展示权限
    showRolePermitList (roleId) {
      this.showPermitTree = true
      const param = {
        roleId: roleId
      }
      this.queryRolePermitList(param)
      this.disableEdit()
    },
    queryRolePermitList (param) {
      const _this = this
      this.fetch(
        this.apiName.queryPermitListByRoleIdList,
        param,
        null,
        responseData => {
          const permitList = responseData.data || []
          _this.rolePermitList = permitList
          // 勾选角色已有权限
          const needExpandTabs = []
          const keyList = []
          permitList.forEach(item => {
            keyList.push(item.id)
            if (needExpandTabs.indexOf(item.clientType) === -1) {
              needExpandTabs.push(item.clientType)
            }
          })
          const trees = _this.$refs.tree
          trees.forEach(tree => {
            tree.setCheckedKeys(keyList)
            tree.filter(permitList)
          })
          _this.showEditBtn = true
          _this.expandAllPermitList(_this.permitRootList, true, needExpandTabs)
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },

    // 更新权限
    updateRolePermitList () {
      const trees = this.$refs.tree
      const len = trees.length
      let permitListArray = []
      this.activeSubSystems = []
      for (let i = 0; i < len; i++) {
        const checkedKeys = trees[i].getCheckedKeys()
        const halfCheckedKeys = trees[i].getHalfCheckedKeys()
        const checkedNodes = trees[i].getCheckedNodes()
        const halfCheckedNodes = trees[i].getHalfCheckedNodes()
        if (checkedKeys.length > 0 || halfCheckedKeys.length > 0) {
          const node = checkedNodes[0] || halfCheckedNodes[0]
          if (this.activeSubSystems.indexOf(node.clientType) === -1) {
            this.activeSubSystems.push(node.clientType)
          }
          const submitKeys = checkedKeys.concat(halfCheckedKeys)
          permitListArray = permitListArray.concat(submitKeys)
        }
      }
      const body = {
        roleId: this.currentSelectRoleId,
        permitList: permitListArray
      }
      const _this = this
      this.fetch(
        this.apiName.bindRolPermitList,
        null,
        body,
        () => {
          _this.editable = false
          _this.showEditBtn = true

          for (const item in trees) {
            trees[item].filter(permitListArray)
          }
          _this.$message({
            showClose: true,
            message: '修改权限成功',
            type: 'success',
            duration: 2000
          })
          _this.disableAllCheckBox(_this.permitRootList)
        },
        responseData => {
          _this.$alert('请求错误：' + responseData.data.message)
        }
      )
    },
    queryAllPermitList () {
      const _this = this
      this.fetch(this.apiName.queryAllPermitList, null, null, responseData => {
        const data = responseData.data || []
        this.mergeButtonListToSubList(data)
        this.disableAllCheckBox(data)
        _this.permitRootList = data
        _this.editable = false
        _this.showEditBtn = true
      })
    },
    mergeButtonListToSubList (data) {
      data = data || []
      data.forEach(item => {
        if (item.subList) {
          this.mergeButtonListToSubList(item.subList)
        } else if (item.buttonList) {
          item.subList = item.buttonList
        }
      })
    }
  }
}
</script>

<style scoped>
</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .current-row {
    background-color: #c9e5f5 !important;
  }

  .role-container .el-collapse {
    overflow-x: hidden !important;
  }

  .role-container .el-collapse .el-collapse-item .el-collapse-item__header {
    height: 30px;
    line-height: 30px;
  }

  .role-container .el-collapse .el-collapse-item .el-collapse-item__header i {
    line-height: 30px;
  }

  .role-container .el-collapse .el-collapse-item .el-collapse-item__content {
    padding-bottom: 5px;
  }

  .role-container
  .el-collapse
  .el-collapse-item
  .el-collapse-item__content
  .el-tree-node__content {
    height: 20px;
    line-height: 20px;
  }

  .roleDialog .el-select .el-input {
    width: 200px;
  }

  .roleDialog .input-with-select .el-input-group__prepend {
    background-color: #fff;
    border: 1px solid #dcdfe6;
    padding: 0;
  }

  .roleDialog .el-form-item__content .el-input {
    max-width: 85%;
  }

  .roleDialog .el-input-group__prepend .el-select {
    margin: -10px 0px;
  }

  /* .roleDialog .el-form-item__content .el-input .el-input__inner{
      margin-left: 10px;
    } */
  .roleDialog .el-form-item__content .el-form-item__error {
    padding-top: 4px !important;
    margin-left: 141px;
  }

  .role-container .el-radio__label {
    padding-left: 0px;
  }
</style>
